package pers.whj.rpc.protocol;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 请求描述信息，server根据此类找出对应的方法执行
 */
public class ServiceDescriptor {
    private String clazz;//类名
    private String method;//方法名
    private String returnType;//返回类型
    private String[] paramTypes;//参数类型

    public ServiceDescriptor(String clazz, String method, String returnType, String[] paramTypes) {
        this.clazz = clazz;
        this.method = method;
        this.returnType = returnType;
        this.paramTypes = paramTypes;
    }

    public ServiceDescriptor() {
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        return this.toString().equals(obj.toString());
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public String toString() {
        return "{clazz=" + this.clazz
                + ", method=" + this.method
                + ", returnType=" + this.returnType
                + ", parameterTypes=" + Arrays.toString(this.paramTypes)
                + "}";
    }

    public String getClazz() {
        return clazz;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getReturnType() {
        return returnType;
    }

    public void setReturnType(String returnType) {
        this.returnType = returnType;
    }

    public String[] getParamTypes() {
        return paramTypes;
    }

    public void setParamTypes(String[] paramTypes) {
        this.paramTypes = paramTypes;
    }

    /**
     * 通过类对象和方法对象，生成服务描述对象
     *
     * @param clazz  类对象
     * @param method 方法
     * @return 服务描述
     */
    public static ServiceDescriptor from(Class clazz, Method method) {
        ServiceDescriptor descriptor = new ServiceDescriptor();
        descriptor.setClazz(clazz.getName());
        descriptor.setMethod(method.getName());
        descriptor.setReturnType(method.getReturnType().getName());
        Class[] paramClasses = method.getParameterTypes();
        String[] paramTypes = new String[paramClasses.length];
        for (int i = 0; i < paramClasses.length; i++) {
            paramTypes[i] = paramClasses[i].getName();
        }
        descriptor.setParamTypes(paramTypes);
        return descriptor;
    }
}
